package managedbean;

import entity.AccessControl;
import entity.AccessRole;
import java.util.ArrayList;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import session.stateless.EmployeeSessionBeanLocal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.component.submenu.Submenu;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.MenuModel;
import java.util.HashSet;
import java.util.Collections;
import session.stateless.LogSessionBeanLocal;

@ManagedBean(name = "loginManagerBean")
@RequestScoped
public class LoginManagerBean {

    @EJB
    EmployeeSessionBeanLocal employeeSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    private String userId;
    private String userPassword;
    private String status;

    // <editor-fold defaultstate="collapsed" desc="Getter & Setter methods. Click on the + sign on the left to edit the code.">
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

// </editor-fold>
    public void loginEmployee(ActionEvent event) {
        switch (employeeSessionBeanLocal.loginEmployee(userId, userPassword)) {
            case -1:
                employeeSessionBeanLocal.updateLogin(userId, 1);
                status = "The user ID or password is incorrect. Please try again.";
                logSessionBeanLocal.addLog("Login", "Login fail (incorrect login): " + userId, "login.xhtml", null);
                break;
            case 0:
                status = "This account is locked. Please contact the adminstrator.";
                logSessionBeanLocal.addLog("Login", "Login fail (account locked): " + userId, "login.xhtml", userId);
                break;
            case 1:
                try {
                    setupModel();

                    String name = employeeSessionBeanLocal.getEmployee(userId).getName();

                    userSessionManagerBean.setUserId(userId);
                    userSessionManagerBean.setName(name);
                    userSessionManagerBean.setOTP(Boolean.FALSE);
                    employeeSessionBeanLocal.updateLogin(userId, 0);

                    logSessionBeanLocal.addLog("Login", "Login success: " + userId, "login.xhtml", userId);

                    FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                            + userSessionManagerBean.getServerPort() + "/MerlionERP-war/index.xhtml");
                } catch (Exception ex) {
                    System.out.println("ERROR AT LOGINMANAGERBEAN loginEmployee CASE 1");
                    ex.printStackTrace();
                }

                break;
            case 2:
                try {
                    setupModel();

                    String name = employeeSessionBeanLocal.getEmployee(userId).getName();

                    userSessionManagerBean.setUserId(userId);
                    userSessionManagerBean.setMessageType("Inbox");
                    userSessionManagerBean.setName(name);
                    userSessionManagerBean.setOTP(true);

                    logSessionBeanLocal.addLog("Login", "Login success (OTP): " + userId, "login.xhtml", userId);

                    FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                            + userSessionManagerBean.getServerPort() + "/MerlionERP-war/changePassword.xhtml");
                } catch (Exception ex) {
                    System.out.println("ERROR AT LOGINMANAGERBEAN loginEmployee CASE 2");
                    ex.printStackTrace();
                }

                break;
        }
    }

    public void setupModel() {
        ArrayList<String> headerList = new ArrayList<String>();
        ArrayList<String> addressList = new ArrayList<String>();
        ArrayList<AccessControl> controlList = new ArrayList<AccessControl>();

        //get access role of customer
        for (AccessRole ar : employeeSessionBeanLocal.getEmployee(userId).getAccessRoles()) {
            //get control for each role
            for (AccessControl ac : ar.getAccessControls()) {
                //get all page title
                headerList.add(ac.getHeader());
                boolean found = false;
                for (int i = 0; i < controlList.size(); i++) {
                    if (controlList.get(i).getTitle().compareTo(ac.getTitle()) == 0) {
                        found = true;
                    }
                }

                if (!found) {
                    //add control that is not found in the list
                    controlList.add(ac);
                }
            }
        }
        HashSet hs = new HashSet();
        hs.addAll(headerList);
        headerList.clear();
        headerList.addAll(hs);
        Collections.sort(headerList);
        MenuModel model = new DefaultMenuModel();

        try {
            for (int i = 0; i < headerList.size(); i++) {

                Submenu submenu = new Submenu();
                submenu.setLabel(headerList.get(i));
                for (AccessControl ac2 : controlList) {
                    if (ac2.getHeader().compareTo(headerList.get(i)) == 0) {
                        addressList.add(ac2.getPageAddress());

                        if (ac2.getRelatedpage() != null) {
                            String[] items = ac2.getRelatedpage().split(";");
                            for (int q = 0; q < items.length; q++) {
                                addressList.add(items[q]);
                            }
                        }

                        MenuItem item = new MenuItem();
                        item.setValue(ac2.getTitle());
                        item.setUrl("http://" + userSessionManagerBean.getServerName() + ":"
                                + userSessionManagerBean.getServerPort() + "/MerlionERP-war/" + ac2.getPageAddress());
                        submenu.getChildren().add(item);
                    }
                }

                model.addSubmenu(submenu);
            }
        } catch (Exception ex) {
            System.out.println("ERROR AT LOGINMANAGERBEAN setupModel()");
            ex.printStackTrace();
        }
        addressList.add("index.xhtml");
        addressList.add("profile.xhtml");
        addressList.add("messages.xhtml");
        addressList.add("replyMessage.xhtml");
        addressList.add("sendMessage.xhtml");
        addressList.add("contactList.xhtml");
        addressList.add("changePassword.xhtml");

        //wx finance
        addressList.add("Web_Finance/addCredit.xhtml");
        addressList.add("Web_Finance/updateCredit.xhtml");
        addressList.add("Web_Finance/viewCredit.xhtml");
        addressList.add("Web_Finance/creditCheck.xhtml");
        addressList.add("Web_Finance/addPayment.xhtml");
        addressList.add("Web_Finance/payments.xhtml");
        addressList.add("Web_Finance/invoices.xhtml");
        addressList.add("Web_Finance/receipts.xhtml");
        addressList.add("Web_Finance/outstandingInvoices.xhtml");
        //wx cancel sales order
        addressList.add("Web_Sales/cancelSalesOrder.xhtml");
//        //wx raw material
//        addressList.add("Web_Production/searchRawMaterials.xhtml");
//        addressList.add("Web_Production/addRawMaterial.xhtml");
//        addressList.add("Web_Production/updateRawMaterial.xhtml");
//        //wx product
//        addressList.add("Web_Production/searchProducts.xhtml");
//        addressList.add("Web_Production/addProduct.xhtml");
//        addressList.add("Web_Production/updateProduct.xhtml");

//        //jas add supplier
//        addressList.add("Web_Warehouse/addSupplier.xhtml");
//        addressList.add("Web_Warehouse/searchSuppliers.xhtml");
//        addressList.add("Web_Warehouse/updateSupplier.xhtml");
//        addressList.add("Web_Warehouse/viewSupplier.xhtml");

//        addressList.add("Web_Warehouse/addShippingOrder.xhtml");
//        addressList.add("Web_Warehouse/searchShippingOrders.xhtml");
//        //wx warehouse
//        addressList.add("Web_Warehouse/searchWarehouses.xhtml");
//        addressList.add("Web_Warehouse/updateWarehouse.xhtml");
//          addressList.add("Web_Warehouse/viewShippingOrder.xhtml");
////        
//        addressList.add("Web_Warehouse/updateWarehouseZone.xhtml");
//        addressList.add("Web_Warehouse/searchWarehouseZones.xhtml");
//        addressList.add("Web_Warehouse/addWarehouseZone.xhtml");
//      
        
        addressList.add("Web_Sales/mySalesOrders.xhtml");
        addressList.add("Web_Sales/salesOrders.xhtml");
        
        //jas add supplier
//        addressList.add("Web_Warehouse/addSupplier.xhtml");
//        addressList.add("Web_Warehouse/searchSuppliers.xhtml");
//        addressList.add("Web_Warehouse/updateSupplier.xhtml");
//        addressList.add("Web_Warehouse/viewSupplier.xhtml");
        addressList.add("Web_Warehouse/viewMaterialRequirementPlans.xhtml");
        addressList.add("Web_Warehouse/searchSuppliersRMPO.xhtml");
        addressList.add("Web_Warehouse/createRawMaterialPurchaseOrder.xhtml");
        addressList.add("Web_Warehouse/searchRawMaterialPurchaseOrders.xhtml");
        addressList.add("Web_Warehouse/viewRawMaterialPurchaseOrder.xhtml");
        addressList.add("Web_Warehouse/receiveRawMaterialPurchaseOrders.xhtml");
        addressList.add("Web_Warehouse/receiveRawMaterialPurchaseOrder.xhtml");
        addressList.add("Web_Warehouse/searchRawMaterialDeliveries.xhtml");
        addressList.add("Web_Warehouse/viewRawMaterialDelivery.xhtml");
        addressList.add("Web_Finance/payForRMPO.xhtml");
        
        System.out.println("Applying access rights...");
        System.out.println("Granted rights to:");
        for (String a : addressList) {
            System.out.println(a);
        }

        userSessionManagerBean.setAddressList(addressList);
        userSessionManagerBean.setModel(model);
    }

    public void forgetPassword(ActionEvent event) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/forget.xhtml"); //redirect to sendMessage.xhtml
        } catch (Exception ex) {
            userSessionManagerBean.setStatus(ex.toString());
        }
    }
}
